package com.gzhryc.shared_device.oem.h5.mng.controllers.bxscn;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNBatteryTypeDayCost;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBatteryType;
import com.gzhryc.shared_device.bxscn.code.dao.models.BXSCNBatteryTypeDayMoneyContent;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNBatteryTypeDayCostService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryTypeService;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyBatteryTypeSearch;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class PortableEnergyBatteryTypeController {

    @Route("/bxscn/device/portable_battery/type/list.html")
    public String list(HttpServletRequest request) {
        return "/bxscn/device/portable_battery/type/list.html";
    }

    @Route(value = "/bxscn/device/portable_battery/type/list.data")
    public ListResult<PortableEnergyBatteryType> listData(HttpServletRequest request) {
        ListResult<PortableEnergyBatteryType> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PortableEnergyBatteryTypeSearch search = WebUtils.getParameter(request, PortableEnergyBatteryTypeSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(PortableEnergyBatteryTypeService.self().countBySearch(search));
        List<PortableEnergyBatteryType> portableEnergyBatteryList = PortableEnergyBatteryTypeService.self().findBySearch(search, pageNo, pageLimit);
        if (portableEnergyBatteryList != null && portableEnergyBatteryList.size() > 0) {
        	String resDomain = WebConstants.getResDomain(request);
            for(PortableEnergyBatteryType batteryType : portableEnergyBatteryList){
                if(StringTools.isNotBlank(batteryType.getThumbnailImg())){
                    batteryType.setThumbnailImg(WebUtils.setHttpDomain(resDomain,batteryType.getThumbnailImg()));
                }
            }
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(portableEnergyBatteryList);
        }
        return result;
    }

    @Route(value = { "/bxscn/device/portable_battery/type/add.html" })
    public String add(HttpServletRequest request) {
        return "/bxscn/device/portable_battery/type/edit.html";
    }

    @Route(value = { "/bxscn/device/portable_battery/type/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增类型失败");
        PortableEnergyBatteryType portableEnergyBatteryType = WebUtils.getParameter(request, PortableEnergyBatteryType.class);
        try {
            portableEnergyBatteryType.setId(portableEnergyBatteryType.getId().toUpperCase());	//必须大写
            if(PortableEnergyBatteryTypeService.self().add(portableEnergyBatteryType)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/bxscn/device/portable_battery/type/update.html" })
    public String update(HttpServletRequest request) {
        String id = WebUtils.getString(request,"id");
        if(StringTools.isNotBlank(id)){
            PortableEnergyBatteryType portableEnergyBatteryType = PortableEnergyBatteryTypeService.self().getById(id);
            WebUtils.setAttribute(request,portableEnergyBatteryType);
        }
        return "/bxscn/device/portable_battery/type/edit.html";
    }

    @Route(value = { "/bxscn/device/portable_battery/type/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改类型失败");
        PortableEnergyBatteryType portableEnergyBatteryType = WebUtils.getParameter(request, PortableEnergyBatteryType.class);
        try {
            portableEnergyBatteryType.setId(portableEnergyBatteryType.getId().toUpperCase());	//必须大写
            if(PortableEnergyBatteryTypeService.self().updateNotNull(portableEnergyBatteryType)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    //电池租金
    @Route(value = { "/bxscn/device/portable_battery/type/day_cost.html" })
    public String dayCost(HttpServletRequest request, HttpSession session) {
        String id = WebUtils.getString(request,"id");
        if(StringTools.isNotBlank(id)){
            PortableEnergyBatteryType portableEnergyBatteryType = PortableEnergyBatteryTypeService.self().getById(id);
            if(portableEnergyBatteryType != null) {
                request.setAttribute("batteryType",portableEnergyBatteryType);

                BXSCNBatteryTypeDayCost batteryTypeDayCost = BXSCNBatteryTypeDayCostService.self().getByTypeId(id);
                if(batteryTypeDayCost == null){
                    batteryTypeDayCost = new BXSCNBatteryTypeDayCost();
                }
                WebUtils.setAttribute(request, batteryTypeDayCost);
                //缓存到内存中
                BXSCNBatteryTypeDayMoneyContent moneyContent = new BXSCNBatteryTypeDayMoneyContent();
                if(StringTools.isNotBlank(batteryTypeDayCost.getDayMoneyContent())){
                    moneyContent = JsonTools.fromJson(batteryTypeDayCost.getDayMoneyContent(),BXSCNBatteryTypeDayMoneyContent.class);
                }
                session.setAttribute(WebConstants.SESSION_BXSCN_BT_DM_CONTENT,moneyContent);
            }
        }
        return "/bxscn/device/portable_battery/type/day_cost.html";
    }

    @Route(value = { "/bxscn/device/portable_battery/type/day_cost/save.do" })
    public AjaxResult doCostShopSave(HttpServletRequest request, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "保存失败");
        BXSCNBatteryTypeDayCost config = WebUtils.getParameter(request, BXSCNBatteryTypeDayCost.class);
        if(config != null){
            Double depositMoney = WebUtils.getDouble(request,"depositMoneyStr");
            if(depositMoney == null || depositMoney < 1 || depositMoney > 5000) {
                result.setMsg("押金设置范围在1-5000元");
                return result;
            }
            config.setDepositMoney(NumberTools.changeMoney(depositMoney));

            Double dayMoney = WebUtils.getDouble(request,"dayMoneyStr");
            if(dayMoney == null || dayMoney < 0.1 || dayMoney > 300) {
                result.setMsg("日租金设置范围在0.1-300元");
                return result;
            }
            config.setDayMoney(NumberTools.changeMoney(dayMoney));

            //从缓存中获取日配置
            BXSCNBatteryTypeDayMoneyContent moneyContent = WebUtils.getAttribute(session,WebConstants.SESSION_BXSCN_BT_DM_CONTENT,BXSCNBatteryTypeDayMoneyContent.class);
            if(moneyContent != null) {
                config.setDayMoneyContent(JsonTools.toJson(moneyContent));
            }
            if(BXSCNBatteryTypeDayCostService.self().save(config)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        }
        return result;
    }

    @Route(value = "/bxscn/device/portable_battery/type/day_cost/item/list.data")
    public ListResult<BXSCNBatteryTypeDayMoneyContent.Item> dayMoneyList(HttpServletRequest request,HttpSession session) {
        ListResult<BXSCNBatteryTypeDayMoneyContent.Item> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        BXSCNBatteryTypeDayMoneyContent moneyContent = WebUtils.getAttribute(session,WebConstants.SESSION_BXSCN_BT_DM_CONTENT,BXSCNBatteryTypeDayMoneyContent.class);
        if(moneyContent != null && moneyContent.getItems() != null && moneyContent.getItems().size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(moneyContent.getItems());
        }
        return result;
    }

    @Route(value = { "/bxscn/device/portable_battery/type/day_cost/item/add.html" })
    public String addDayMoney(HttpServletRequest request) {
        return "/bxscn/device/portable_battery/type/day_money.html";
    }

    @Route(value = { "/bxscn/device/portable_battery/type/day_cost/item/update.html" })
    public String updateDayMoney(HttpServletRequest request,HttpSession session) {
        Integer leaseDay = WebUtils.getInteger(request,"leaseDay");
        if(leaseDay != null) {
            BXSCNBatteryTypeDayMoneyContent moneyContent = WebUtils.getAttribute(session,WebConstants.SESSION_BXSCN_BT_DM_CONTENT,BXSCNBatteryTypeDayMoneyContent.class);
            if (moneyContent != null && moneyContent.getItems() != null && moneyContent.getItems().size() > 0) {
                for(BXSCNBatteryTypeDayMoneyContent.Item item : moneyContent.getItems()){
                    if(item.getLeaseDay().equals(leaseDay)){
                        WebUtils.setAttribute(request,item);
                        break;
                    }
                }
            }
        }
        return "/bxscn/device/portable_battery/type/day_money.html";
    }

    @Route(value = { "/bxscn/device/portable_battery/type/day_cost/item/save.do" })
    public AjaxResult doAddDayMoney(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "保存租期阶梯租金失败");
        BXSCNBatteryTypeDayMoneyContent.Item moneyContentItem = WebUtils.getParameter(request, BXSCNBatteryTypeDayMoneyContent.Item.class);
        if (moneyContentItem != null && moneyContentItem.getLeaseDay() != null) {
            Double moneyStr = WebUtils.getDouble(request, "moneyStr");
            if (moneyStr == null || moneyStr < 0.1 || moneyStr > 300) {
                result.setMsg("租金金额设置范围在0.1-300元");
                return result;
            }
            moneyContentItem.setMoney(NumberTools.changeMoney(moneyStr));

            BXSCNBatteryTypeDayMoneyContent moneyContent = WebUtils.getAttribute(session, WebConstants.SESSION_BXSCN_BT_DM_CONTENT, BXSCNBatteryTypeDayMoneyContent.class);
            if (moneyContent == null) {
                moneyContent = new BXSCNBatteryTypeDayMoneyContent();
            }

            int index = moneyContent.getItems().size();
            for (int i = 0; i < moneyContent.getItems().size(); i++) {
                BXSCNBatteryTypeDayMoneyContent.Item item = moneyContent.getItems().get(i);
                if (item.getLeaseDay().equals(moneyContentItem.getLeaseDay())) {
                    item.setMoney(moneyContentItem.getMoney());
                    index = -1;
                    break;
                }

                if (item.getLeaseDay() > moneyContentItem.getLeaseDay()) {
                    index = i;
                    break;
                }
            }

            if (index > -1) {
                moneyContent.getItems().add(index, moneyContentItem);
                session.setAttribute(WebConstants.SESSION_BXSCN_BT_DM_CONTENT, moneyContent);
            }
            result.setCode(DtoConstants.SUCCESS, null);
        }
        return result;
    }

    @Route(value = { "/bxscn/device/portable_battery/type/day_cost/item/del.do" })
    public AjaxResult doDelSetMeal(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除租期阶梯租金失败");
        Integer leaseDay = WebUtils.getInteger(request,"leaseDay");
        if(leaseDay != null) {
            BXSCNBatteryTypeDayMoneyContent moneyContent = WebUtils.getAttribute(session, WebConstants.SESSION_BXSCN_BT_DM_CONTENT, BXSCNBatteryTypeDayMoneyContent.class);
            if (moneyContent != null && moneyContent.getItems() != null && moneyContent.getItems().size() > 0) {
                int index = -1;
                for (int i = 0; i < moneyContent.getItems().size(); i++) {
                    BXSCNBatteryTypeDayMoneyContent.Item item = moneyContent.getItems().get(i);
                    if (item.getLeaseDay().equals(leaseDay)) {
                        index = i;
                        break;
                    }
                }

                if (index > -1) {
                    moneyContent.getItems().remove(index);
                    session.setAttribute(WebConstants.SESSION_BXSCN_BT_DM_CONTENT, moneyContent);
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            }
        }
        return result;
    }

    @Route(value = { "/bxscn/device/portable_battery/type/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除类型失败");
        String id = WebUtils.getString(request,"id");
        try {
            if(PortableEnergyBatteryTypeService.self().deleteById(id)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/bxscn/device/portable_battery/type/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        PortableEnergyBatteryTypeSearch search = new PortableEnergyBatteryTypeSearch();
        search.setName(term);
        Long total = 0L;
        List<PortableEnergyBatteryType> list = PortableEnergyBatteryTypeService.self()
                .findBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (PortableEnergyBatteryType batteryType : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(batteryType.getId());
                item.setText(batteryType.getName() + "("+batteryType.getId()+")");
                result.getBody().getData().add(item);
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
}
